/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: GuillotineFileAppender.java 620 2007-05-15 07:58:47Z jacek.kolezynski $
 */
package logmatcher.log4j;

import logmatcher.utils.TimestampGenerator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.spi.LoggingEvent;

import java.io.File;
import java.io.IOException;


/**
*  DOCUMENT ME!
*
*  @version $Revision: 620 $
 */
public class GuillotineFileAppender extends FileAppender {
    //~ Static fields/initializers -------------------------------------------------------------------------------------

    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(GuillotineFileAppender.class);

    //~ Instance fields ------------------------------------------------------------------------------------------------

    /** TODO: DOCUMENT ME! */
    private String endMessage = "--- END OF TEST ---";

    /** TODO: DOCUMENT ME! */
    private String outputExtension = ".log";

    //~ Constructors ---------------------------------------------------------------------------------------------------

/**
     *  Creates a new GuillotineFileAppender object.
     *
     *  @param trigger TODO: DOCUMENT ME!
    */
    public GuillotineFileAppender() {
    }


/**
     *  Creates a new GuillotineFileAppender object.
     *
     *  @param trigger TODO: DOCUMENT ME!
    */
    public GuillotineFileAppender(String endMessage) {
        this.endMessage = endMessage;
    }


/**

     *  DOCUMENT ME!

     *

     *  @param layout

     *  @param filename

     *  @param trigger TODO: DOCUMENT ME!

     *

     *  @throws IOException

    */
    public GuillotineFileAppender(Layout layout, String filename, String endMessage)
        throws IOException {
        super(layout, filename);

        this.endMessage = endMessage;
    }


/**

     *  DOCUMENT ME!

     *

     *  @param layout

     *  @param filename

     *  @param append

     *  @param trigger TODO: DOCUMENT ME!

     *

     *  @throws IOException

    */
    public GuillotineFileAppender(Layout layout, String filename, String endMessage, boolean append)
        throws IOException {
        super(layout, filename, append);

        this.endMessage = endMessage;
    }


/**

     *  DOCUMENT ME!

     *

     *  @param layout

     *  @param filename

     *  @param append

     *  @param bufferedIO

     *  @param bufferSize

     *  @param trigger TODO: DOCUMENT ME!

     *

     *  @throws IOException

    */
    public GuillotineFileAppender(
        Layout layout, String filename, String endMessage, boolean append, boolean bufferedIO, int bufferSize)
        throws IOException {
        super(layout, filename, append, bufferedIO, bufferSize);

        this.endMessage = endMessage;
    }

    //~ Methods --------------------------------------------------------------------------------------------------------

    /**
    *  DOCUMENT ME!
    *
    *  @todo DOCUMENT ME!
    */
    public void activateOptions() {
        super.activateOptions();

        if (fileName != null) {
            //            File file = new File(fileName);

            //            scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
        } else {
            LOGGER.error("File is not set for appender [" + name + "].");
        }
    }


    /**
    *  DOCUMENT ME!
    *
    *  @return TODO: DOCUMENT ME!
    *
    *  @todo DOCUMENT ME!
    */
    public String getEndMessage() {
        return endMessage;
    }


    /**
    *  DOCUMENT ME!
    *
    *  @return TODO: DOCUMENT ME!
    *
    *  @todo DOCUMENT ME!
    */
    public String getOutputExtension() {
        return outputExtension;
    }


    /**
    *  DOCUMENT ME!
    *
    *  @param endMessage TODO: DOCUMENT ME!
    *
    *  @todo DOCUMENT ME!
    */
    public void setEndMessage(String endMessage) {
        this.endMessage = endMessage;
    }


    /**
    *  DOCUMENT ME!
    *
    *  @param outputExtension TODO: DOCUMENT ME!
    *
    *  @todo DOCUMENT ME!
    */
    public void setOutputExtension(String outputExtension) {
        this.outputExtension = outputExtension;
    }


    /**
    *  This method differentiates DailyRollingFileAppender from its super class.<p>Before actually logging,
    *  this method will check whether it is time to do a rollover. If it is, it will schedule the next rollover time
    *  and then rollover.</p>
    *
    *  @param event TODO: DOCUMENT ME!
    */
    protected void subAppend(LoggingEvent event) {
        super.subAppend(event);

        String msg = String.valueOf(event.getMessage());

        if (msg.contains(endMessage)) {
            try {
                rollOver();
            } catch (IOException ioe) {
                LOGGER.error("rollOver() failed.", ioe);
            }
        }
    }


    /**
    *  Rollover the current file to a new file.
    *
    *  @throws IOException TODO: DOCUMENT ME!
    */
    private void rollOver() throws IOException {
        // The log file will be renamed to the value of the scheduledFilename variable when the trigger value

        // comes to the appender.
        String scheduledFilename;

        scheduledFilename = fileName.substring(0, fileName.lastIndexOf(".")) + "_"
            + TimestampGenerator.getTimestamp("yyyyMMddHHmmssSS") + outputExtension;

        LOGGER.debug("Scheduled filename : " + scheduledFilename);
        
        this.closeFile();
        
        File target = new File(scheduledFilename);

        if (target.exists()) {
            target.delete();
        }        
        
        File file = new File(fileName);
               
        boolean result = file.renameTo(target);                  

        //file.delete();

        try {
            // This will also close the file. This is OK since multiple
            // close operations are safe.
            this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
        } catch (IOException e) {
            errorHandler.error("setFile(" + fileName + ", false) call failed.");
        }
        
        if (result) {
            LOGGER.debug(fileName + " -> " + scheduledFilename);            
        } else {
            LOGGER.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");                     
        }
    }
}
